package com.zq.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zq.common.exception.ResultException;
import com.zq.common.util.JwtUtil;
import com.zq.order.dao.dto.OrderStatisticsDto;
import com.zq.order.dao.entity.OrderInfo;
import com.zq.order.dao.entity.OrderItem;
import com.zq.order.dao.entity.OrderStatistics;
import com.zq.order.dao.vo.OrderListVo;
import com.zq.order.dao.vo.OrderStatisticsVo;
import com.zq.order.mapper.OrderInfoMapper;
import com.zq.order.mapper.OrderItemMapper;
import com.zq.order.mapper.OrderStatisticsMapper;
import com.zq.order.service.IOrderInfoService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author 张乔
 * @since 2025-05-20
 */
@Service
@Slf4j
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {


    @Resource
    private OrderStatisticsMapper orderStatisticsMapper;


    //    根据时间范围查询订单统计数据
    @Override
    public OrderStatisticsVo getOrderStatisticsData(OrderStatisticsDto orderStatisticsDto) {
        // 查询统计结果数据
        LambdaQueryWrapper<OrderStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(StringUtils.hasText(orderStatisticsDto.getCreateTimeBegin()),
                OrderStatistics::getOrderDate, orderStatisticsDto.getCreateTimeBegin()
        ).le(StringUtils.hasText(orderStatisticsDto.getCreateTimeEnd()),
                OrderStatistics::getOrderDate, orderStatisticsDto.getCreateTimeEnd());
        List<OrderStatistics> orderStatisticsList = orderStatisticsMapper.selectList(queryWrapper) ;
        // 创建一个 DateTimeFormatter 实例，指定日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        //日期列表
        List<String> dateList = orderStatisticsList.stream().
                map(orderStatistics -> orderStatistics.getOrderDate().format(formatter)).toList();
//        List<LocalDate> dateList =orderStatisticsList.stream().
//                map(OrderStatistics::getOrderDate).toList();
        //统计金额列表
        List<BigDecimal> amountList = orderStatisticsList.stream().
                map(OrderStatistics::getTotalAmount).collect(Collectors.toList());
        // 创建OrderStatisticsVo对象封装响应结果数据
        OrderStatisticsVo orderStatisticsVo = new OrderStatisticsVo() ;
        orderStatisticsVo.setDateList(dateList);
        orderStatisticsVo.setAmountList(amountList);

        // 返回数据
        return orderStatisticsVo;
    }
@Resource
private OrderInfoMapper orderInfoMapper;

    //    分页条件查询订单列表
    @Override
    public PageInfo<OrderListVo> getPages(Integer page,
                                          Integer limit,
                                          String consigneeName) {

        PageHelper.startPage(page, limit);
//        查询订单列表，并返回特定的数据
    List<OrderListVo> orderListVos=    orderInfoMapper.selectListOrderVo(consigneeName);
//        List<OrderInfo> orderList = this.list(new LambdaQueryWrapper<OrderInfo>().
//                like(StringUtils.hasText(consigneeName), OrderInfo::getReceiverName, consigneeName));
//
//        List<OrderListVo> orderListVos = new ArrayList<>();
//orderList.forEach(orderInfo -> {
//    OrderListVo orderListVo = new OrderListVo();
//    BeanUtils.copyProperties(orderInfo, orderListVo);
//    orderListVos.add(orderListVo);
//});
            PageInfo<OrderListVo> pageInfo = new PageInfo<>(orderListVos);
log.info("查询订单列表成功"+pageInfo.getTotal());
        return pageInfo;
    }

    @Override
    public void saveOrder(OrderListVo orderListVo) {
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(orderListVo, orderInfo);
        this.save(orderInfo);
    }

    @Override
    public void updateOrder(OrderListVo orderListVo) {
OrderInfo orderInfo = new OrderInfo();
BeanUtils.copyProperties(orderListVo, orderInfo);
this.updateById(orderInfo);
    }

    @Override
    public void deleteOrder(Long id) {
this.removeById(id);
    }

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private OrderItemMapper orderItemMapper;

    @Override
    public PageInfo<OrderInfo> getPagesByproductName(Integer page, Integer limit,
                                                     String productName,
                                                     String userToken) {
        Integer userId = jwtUtil.getUsernameFromToken(userToken);
        if (userId == null) {
            throw new  ResultException(500,"用户不存在");
        }
        PageHelper.startPage(page, limit);
        List<OrderInfo> orderInfos = this.list(new LambdaQueryWrapper<OrderInfo>().
                eq(OrderInfo::getUserId, userId)
                .orderByDesc(OrderInfo::getCreateTime)
        );

orderInfos.forEach(orderInfo -> {

    List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().
            eq(OrderItem::getOrderId, orderInfo.getId())
            .like(StringUtils.hasText(productName), OrderItem::getSkuName, productName)
    );
    orderInfo.setOrderItems(orderItems);

});


        return new PageInfo<>(orderInfos);
    }







}


